package com.kelai.resource.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kelai.domain.*;
import com.kelai.resource.IMarketActivityResource;
import com.kelai.resource.JsonCommonResource;
import com.kelai.response.JsonResponse;
import com.kelai.response.Response;
import com.kelai.service.ICommonService;
import com.kelai.service.IMarketService;
import com.kelai.service.impl.DefaultCommonService;
import com.kelai.utils.BreezeeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 市场活动资源服务实现类
 * Created by Silence on 2016/11/26.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/market")
public class DefaultMarketActivityResource extends JsonCommonResource implements IMarketActivityResource {

    @Resource
    private IMarketService marketService;

    private ICommonService marketActivityService;
    private ICommonService customerService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public Response<MarketActivityEntity> page(@RequestBody MarketActivityEntity marketActivityEntity) {

        /**
         * TODO 查询条件 以店铺名称来查，暂时未完成，待完善
         */
        /*String customerName = (String) marketActivityEntity.getProperties().get("customers_id_obj_in_ae");
        if (StringUtils.isNotEmpty(customerName)) {
            CustomerEntity customerEntity = new CustomerEntity();
            customerEntity.getProperties().put("category", "3");
            customerEntity.getProperties().put("name_like", customerName);
            List<AbstractEntity> customerList = customerService.listAll(customerEntity);
            List<String> customerIdList = Lists.newArrayList();
            customerList.forEach(item -> {
                customerIdList.add(item.getId());
            });
            String customerIds = Joiner.on(",").join(customerIdList);
            marketActivityEntity.getProperties().put("customers_id_obj_in_ae", customerIds);
        }*/

        Object startDateGt = marketActivityEntity.getProperties().get("startDate_gt");
        Object startDateLe = marketActivityEntity.getProperties().get("startDate_le");
        Object endDateGt = marketActivityEntity.getProperties().get("endDate_gt");
        Object endDateLe = marketActivityEntity.getProperties().get("endDate_le");
        checkDate(marketActivityEntity,startDateGt,startDateLe,endDateGt,endDateLe);

        return _pageAll(marketActivityService, marketActivityEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public Response<MarketActivityEntity> findById(@PathVariable String id) {
        return _findOne(marketActivityService, id, 0);
    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public Response<MarketActivityEntity> findByCode(@PathVariable String code) {
        return _findOne(marketActivityService, code, 1);
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public Response<MarketActivityEntity> save(@RequestBody MarketActivityEntity marketActivityEntity) {

        Map<String,Object> properties = marketActivityEntity.getProperties();

        String startDateStr = properties.get("startDate").toString();
        Date startDate = BreezeeUtils.strToDateTime(startDateStr,BreezeeUtils.FORMAT_LONG);
        String endDateStr = properties.get("endDate").toString();
        Date endDate = BreezeeUtils.strToDateTime(endDateStr,BreezeeUtils.FORMAT_LONG);

        List<String> cusIds = (List<String>)properties.get("cusIds");
        String code = properties.get("code").toString();
        String name = properties.get("name").toString();
        String pkId = properties.get("id").toString();

        List<CustomerEntity> customers = cusIds.stream()
                .map(id -> (CustomerEntity)customerService.findById(id))
                .collect(Collectors.toList());

        MarketActivityEntity entity = new MarketActivityEntity();
        if(StringUtils.isNotEmpty(pkId)){
            entity = (MarketActivityEntity)marketActivityService.findById(pkId);
        }
        entity.setCode(code);
        entity.setName(name);
        entity.setStartDate(startDate);
        entity.setEndDate(endDate);
        entity.setCustomers(customers);

        return _saveInfo(marketService, entity);
    }

    /**
     * 分析
     * @param marketActivityEntity 查询条件
     * @return
     */
    @RequestMapping(value = "/analysis", method = RequestMethod.POST)
    public Response<AbstractEntity> analysis(@RequestBody MarketActivityEntity marketActivityEntity) {

        JsonResponse rep = JsonResponse.OK();

        Object marketId = marketActivityEntity.getProperties().get("_marketId");
        MarketActivityEntity dbMarketActivityEntity =
                (MarketActivityEntity)marketActivityService.findById(marketId.toString());
        Date startDate = dbMarketActivityEntity.getStartDate();
        Date endDate = dbMarketActivityEntity.getEndDate();
        List<CustomerEntity> customerList = dbMarketActivityEntity.getCustomers();
        List<String> shopList = Lists.newArrayList();
        customerList.forEach( item -> shopList.add(item.getId()));

        Map<String, Object> conditions = Maps.newConcurrentMap();
        conditions.put("_shopIds",shopList);
        conditions.put("_startDate", LocalDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault()).toLocalDate().toString());
        conditions.put("_endDate", LocalDateTime.ofInstant(endDate.toInstant(), ZoneId.systemDefault()).toLocalDate().toString());

        rep = _pageAllByBi("SHOP_DAY", conditions);

        return rep;

    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public Response<MarketActivityEntity> delete(@PathVariable String id) {
        return _delete(marketActivityService, id);
    }

    @Override
    public void initService() {
        if (marketActivityService == null)
            marketActivityService = new DefaultCommonService("marketActivityRepository");
        if (customerService == null)
            customerService = new DefaultCommonService("customerRepository");
    }

    private void checkDate(AbstractEntity entity, Object startDateGt, Object startDateLe ,Object endDateGt, Object endDateLe) {
        try {
            if (startDateGt != null)
                entity.getProperties().put("startDate_gt", BreezeeUtils.DATE_FORMAT_LONG.parse(startDateGt.toString()+" 00:00:00"));
            if (startDateLe != null)
                entity.getProperties().put("startDate_le", BreezeeUtils.DATE_FORMAT_LONG.parse(startDateLe.toString()+" 23:59:59"));
            if (endDateGt != null)
                entity.getProperties().put("endDate_gt", BreezeeUtils.DATE_FORMAT_LONG.parse(endDateGt.toString()+" 00:00:00"));
            if (endDateLe != null)
                entity.getProperties().put("endDate_le", BreezeeUtils.DATE_FORMAT_LONG.parse(endDateLe.toString()+" 23:59:59"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
